//
//  UserAccount.swift
//  weibo
//
//  Created by Fosen on 15/11/29.
//  Copyright © 2015年 fosen. All rights reserved.
//

import UIKit

class UserAccount: NSObject ,NSCoding{
    //用于调用access_token，接口获取授权后的access token
    var access_token :String?
//    	access_token的生命周期，单位是秒数。
    var expires_in :NSTimeInterval = 0{
        didSet{
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    //计算型属性计算token失效的日期   开发者账号的有效期是5年 普通用户的有效期是3天  未审核通过的token有效期是一天
    var expires_date :NSDate?
//    access_token的生命周期（该参数即将废弃，开发者请使用expires_in
//    let remind_in :String
    //当前授权用户的id
    var uid :String?
    
    //友好显示名称
    var name :String?
    
    //用户头像地址（） 180*180
    var avatar_large: String?
    
    init(dict : [String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    func saveAccount(){
        //保存到沙盒路径  stringbyappendingpathcomment
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
//        print(path)
        //归档
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
        
    }
    
    //从磁盘中获取自定义对象
    class func loadAccount() -> UserAccount? {
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
        //解归档
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount{
            
            //添加过期日期对象
            if account.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            return account
            }
        }
        return nil
    }
    
    //过滤
    override func setValue(value: AnyObject?, forUndefinedKey key: String) { }

    
    //重写discribe 属性
    override var description :String{
        
        let keys = ["access_token","expires_in","uid","name","avatar_large","expires_date"]
        return  dictionaryWithValuesForKeys(keys).description
    }
    
    //实现NScoding 的协议方法
    //解归档   二进制-》对象   与反序列化 相似
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String

    }
    
    //归档  对象 —> 二进制  与序列化 相似
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token,forKey: "access_token")
        aCoder.encodeObject(expires_date,forKey: "expires_date")
        aCoder.encodeObject(uid,forKey: "uid")
        aCoder.encodeObject(name,forKey: "name")
        aCoder.encodeObject(avatar_large,forKey: "avatar_large")

    }

}
